import { WebsiteModel } from '../models/Website';
import { GroupModel } from '../models/Group';
import { 
  Website, 
  CreateWebsiteRequest, 
  UpdateWebsiteRequest,
  ApiResponse,
  PaginatedResponse,
  PaginationQuery
} from '../types/group';

export class WebsiteService {
  // 获取所有网站
  static async getAllWebsites(): Promise<ApiResponse<Website[]>> {
    try {
      const websites = await WebsiteModel.findAll();
      return {
        success: true,
        message: '获取网站列表成功',
        data: websites
      };
    } catch (error) {
      return {
        success: false,
        message: '获取网站列表失败'
      };
    }
  }

  // 根据分组ID获取网站
  static async getWebsitesByGroupId(groupId: string): Promise<ApiResponse<Website[]>> {
    try {
      // 检查分组是否存在
      const group = await GroupModel.findById(groupId);
      if (!group) {
        return {
          success: false,
          message: '分组不存在'
        };
      }

      const websites = await WebsiteModel.findByGroupId(groupId);
      return {
        success: true,
        message: '获取网站列表成功',
        data: websites
      };
    } catch (error) {
      return {
        success: false,
        message: '获取网站列表失败'
      };
    }
  }

  // 获取网站详情
  static async getWebsiteById(id: string): Promise<ApiResponse<Website>> {
    try {
      const website = await WebsiteModel.findById(id);
      if (!website) {
        return {
          success: false,
          message: '网站不存在'
        };
      }

      return {
        success: true,
        message: '获取网站详情成功',
        data: website
      };
    } catch (error) {
      return {
        success: false,
        message: '获取网站详情失败'
      };
    }
  }

  // 创建网站
  static async createWebsite(data: CreateWebsiteRequest): Promise<ApiResponse<Website>> {
    try {
      // 验证必填字段
      if (!data.name || data.name.trim().length === 0) {
        return {
          success: false,
          message: '网站名称不能为空'
        };
      }

      if (!data.url || data.url.trim().length === 0) {
        return {
          success: false,
          message: '网站URL不能为空'
        };
      }

      if (!data.groupId || data.groupId.trim().length === 0) {
        return {
          success: false,
          message: '必须选择分组'
        };
      }

      // 验证URL格式
      try {
        new URL(data.url);
      } catch {
        return {
          success: false,
          message: 'URL格式不正确'
        };
      }

      // 检查分组是否存在
      const group = await GroupModel.findById(data.groupId);
      if (!group) {
        return {
          success: false,
          message: '选择的分组不存在'
        };
      }

      // 检查URL是否已存在
      const urlExists = await WebsiteModel.existsByUrl(data.url.trim());
      if (urlExists) {
        return {
          success: false,
          message: '该URL已存在'
        };
      }

      const website = await WebsiteModel.create({
        ...data,
        name: data.name.trim(),
        url: data.url.trim(),
        description: data.description?.trim()
      });

      return {
        success: true,
        message: '创建网站成功',
        data: website
      };
    } catch (error) {
      return {
        success: false,
        message: '创建网站失败'
      };
    }
  }

  // 更新网站
  static async updateWebsite(id: string, data: UpdateWebsiteRequest): Promise<ApiResponse<Website>> {
    try {
      // 检查网站是否存在
      const existingWebsite = await WebsiteModel.findById(id);
      if (!existingWebsite) {
        return {
          success: false,
          message: '网站不存在'
        };
      }

      // 验证字段
      if (data.name !== undefined) {
        if (!data.name || data.name.trim().length === 0) {
          return {
            success: false,
            message: '网站名称不能为空'
          };
        }
        data.name = data.name.trim();
      }

      if (data.url !== undefined) {
        if (!data.url || data.url.trim().length === 0) {
          return {
            success: false,
            message: '网站URL不能为空'
          };
        }

        // 验证URL格式
        try {
          new URL(data.url);
        } catch {
          return {
            success: false,
            message: 'URL格式不正确'
          };
        }

        // 检查URL是否已存在（排除当前网站）
        const urlExists = await WebsiteModel.existsByUrl(data.url.trim(), id);
        if (urlExists) {
          return {
            success: false,
            message: '该URL已存在'
          };
        }

        data.url = data.url.trim();
      }

      if (data.groupId !== undefined) {
        if (!data.groupId || data.groupId.trim().length === 0) {
          return {
            success: false,
            message: '必须选择分组'
          };
        }

        // 检查分组是否存在
        const group = await GroupModel.findById(data.groupId);
        if (!group) {
          return {
            success: false,
            message: '选择的分组不存在'
          };
        }
      }

      if (data.description !== undefined && data.description) {
        data.description = data.description.trim();
      }

      const updatedWebsite = await WebsiteModel.update(id, data);
      if (!updatedWebsite) {
        return {
          success: false,
          message: '更新网站失败'
        };
      }

      return {
        success: true,
        message: '更新网站成功',
        data: updatedWebsite
      };
    } catch (error) {
      return {
        success: false,
        message: '更新网站失败'
      };
    }
  }

  // 删除网站
  static async deleteWebsite(id: string): Promise<ApiResponse<void>> {
    try {
      // 检查网站是否存在
      const existingWebsite = await WebsiteModel.findById(id);
      if (!existingWebsite) {
        return {
          success: false,
          message: '网站不存在'
        };
      }

      const deleted = await WebsiteModel.delete(id);
      if (!deleted) {
        return {
          success: false,
          message: '删除网站失败'
        };
      }

      return {
        success: true,
        message: '删除网站成功'
      };
    } catch (error) {
      return {
        success: false,
        message: '删除网站失败'
      };
    }
  }

  // 搜索网站
  static async searchWebsites(query: string): Promise<ApiResponse<Website[]>> {
    try {
      if (!query || query.trim().length === 0) {
        return {
          success: false,
          message: '搜索关键词不能为空'
        };
      }

      const websites = await WebsiteModel.search(query.trim());
      return {
        success: true,
        message: `找到 ${websites.length} 个相关网站`,
        data: websites
      };
    } catch (error) {
      return {
        success: false,
        message: '搜索网站失败'
      };
    }
  }

  // 切换网站状态
  static async toggleWebsiteStatus(id: string): Promise<ApiResponse<Website>> {
    try {
      const website = await WebsiteModel.toggleActive(id);
      if (!website) {
        return {
          success: false,
          message: '网站不存在'
        };
      }

      return {
        success: true,
        message: `网站已${website.isActive ? '启用' : '禁用'}`,
        data: website
      };
    } catch (error) {
      return {
        success: false,
        message: '切换网站状态失败'
      };
    }
  }

  // 重新排序网站
  static async reorderWebsites(websiteOrders: { id: string; order: number }[]): Promise<ApiResponse<void>> {
    try {
      // 验证所有网站是否存在
      for (const { id } of websiteOrders) {
        const website = await WebsiteModel.findById(id);
        if (!website) {
          return {
            success: false,
            message: `网站 ${id} 不存在`
          };
        }
      }

      await WebsiteModel.reorder(websiteOrders);

      return {
        success: true,
        message: '网站排序更新成功'
      };
    } catch (error) {
      return {
        success: false,
        message: '网站排序更新失败'
      };
    }
  }

  // 批量移动网站到新分组
  static async moveWebsitesToGroup(websiteIds: string[], newGroupId: string): Promise<ApiResponse<{ movedCount: number }>> {
    try {
      // 检查分组是否存在
      const group = await GroupModel.findById(newGroupId);
      if (!group) {
        return {
          success: false,
          message: '目标分组不存在'
        };
      }

      let movedCount = 0;
      for (const websiteId of websiteIds) {
        const website = await WebsiteModel.findById(websiteId);
        if (website) {
          await WebsiteModel.update(websiteId, { groupId: newGroupId });
          movedCount++;
        }
      }

      return {
        success: true,
        message: `成功移动 ${movedCount} 个网站到新分组`,
        data: { movedCount }
      };
    } catch (error) {
      return {
        success: false,
        message: '批量移动网站失败'
      };
    }
  }

  // 获取网站统计信息
  static async getWebsiteStats(): Promise<ApiResponse<{
    total: number;
    active: number;
    inactive: number;
    byGroup: { groupId: string; groupName: string; count: number }[];
  }>> {
    try {
      const websites = await WebsiteModel.findAll();
      const groups = await GroupModel.findAll();

      const total = websites.length;
      const active = websites.filter(w => w.isActive).length;
      const inactive = total - active;

      const byGroup = groups.map(group => ({
        groupId: group.id,
        groupName: group.name,
        count: websites.filter(w => w.groupId === group.id).length
      }));

      return {
        success: true,
        message: '获取网站统计信息成功',
        data: {
          total,
          active,
          inactive,
          byGroup
        }
      };
    } catch (error) {
      return {
        success: false,
        message: '获取网站统计信息失败'
      };
    }
  }
}